<?php

namespace App\Repository;

use App\Consts\MessageConst;
use App\Consts\SmsConst;
use App\Models\MsgSend;
use \Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

/**
 * 消息发送记录仓库
 * Class MsgSendRepository
 * @package App\Repository
 */
class MsgSendRepository extends BaseRepository
{

    /**
     * MsgSendRepository constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new MsgSend();
    }

    /**
     * 根据条件获取搜索列表
     * @param array $condition
     * @return array
     */
    public function getSearchListByCondition($condition = [])
    {
        $query = $this->model
            ->where(function (Builder $query) use ($condition) {
                if (!empty($condition['platform_id'])) {
                    $query->where('platform_id', $condition['platform_id']);
                }
                if (!empty($condition['channel_id'])) {
                    $query->where('channel_id', $condition['channel_id']);
                }
                if (!empty($condition['scene_id'])) {
                    $query->where('scene_id', $condition['scene_id']);
                }
                if (!empty($condition['msg_type'])) {
                    $query->where('msg_type', $condition['msg_type']);
                }
                if (!empty($condition['mobile'])) {
                    $query->where('mobile', $condition['mobile']);
                }
                if (!empty($condition['realname'])) {
                    $query->where('realname', 'like', '%' . $condition['realname'] . '%');
                }
                if (!empty($condition['city'])) {
                    $query->where('city', $condition['city']);
                }
                if (!empty($condition['campus'])) {
                    $query->where('campus', $condition['campus']);
                }
                if (!empty($condition['start_time']) && !empty($condition['end_time'])) {
                    $query->whereBetween('create_time', [$condition['start_time'], $condition['end_time']]);
                }
                if (isset($condition['status'])) {
                    $query->where('status', $condition['status']);
                }
            })
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->select(['id', 'channel_id', 'scene_id', 'msg_type', 'template', 'realname', 'mobile', 'role',
                'city', 'campus', 'body', 'result', 'status', 'remark', 'create_time']);
        $count = $query->count();
        if ($count) {
            $list = $query->limit($condition['limit'])
                ->offset($condition['offset'])
                ->orderBy($condition['order_field'], $condition['order_type'])
                ->get();
            $list = $list ? $list->toArray() : [];
        } else {
            $list = [];
        }
        return ['total' => $count, 'rows' => $list];
    }

    /**
     * 获取消息渠道统计数据
     * @param $channelId
     * @param $timeAry
     * @param $msgType
     * @param null $template
     * @param null $status
     * @return mixed
     */
    public function getCountByChannelIdAndTime($channelId, $timeAry, $msgType = null, $template = null, $status = null)
    {
        $count = $this->model
            ->where('channel_id', $channelId)
            ->whereBetween('create_time', $timeAry)
            ->where(function (Builder $query) use ($msgType, $template, $status) {
                if (!is_null($status)) {
                    $query->where('status', $status);
                }
                if (!is_null($msgType)) {
                    $query->where('msg_type', $msgType);
                }
                if (!is_null($template)) {
                    $query->where('template', $template);
                }
            })
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->count();
        return $count ? $count : 0;
    }

    /**
     * 根据 ID 获取详情
     * @param $messageId
     * @param array $field
     * @return array
     */
    public function getInfoById($messageId, $field = ['*'])
    {
        $info = $this->model
            ->where('id', $messageId)
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->select($field)
            ->first();
        return $info ? $info->toArray() : [];
    }

    /**
     * 根据任务 ID 获取消息详情
     * @param $taskId
     * @return array|string
     */
    public function getInfoByTaskId($taskId)
    {
        $info = $this->model
            ->where('task_id', $taskId)
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->first();
        return $info ? $info->toArray() : '';
    }

    /**
     * 根据任务 ID 获取推送状态
     * @param $taskId
     * @return int|mixed
     */
    public function getStatusByTaskId($taskId)
    {
        $info = $this->model
            ->where('task_id', $taskId)
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->value('status');
        return $info ? $info : null;
    }

    /**
     * 根据任务 ID 和手机号获取验证码
     * @param $taskId
     * @param $mobile
     * @return mixed|string
     */
    public function getCodeByTaskIdAndMobile($taskId, $mobile)
    {
        $info = $this->model
            ->where('task_id', $taskId)
            ->where('mobile', $mobile)
            ->where('create_time', '>', time() - SmsConst::SMS_CODE_EXPIRED)
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->orderByDesc('id')
            ->value('code');
        return $info ? $info : '';
    }

    /**
     * 更新任务推送状态
     * @param $taskId
     * @param $status
     * @param string $remark
     * @return int
     */
    public function updateStatusByTaskId($taskId, $status, $remark = '')
    {
        return $this->model
            ->where('task_id', $taskId)
            ->where('status', '<>',MessageConst::STATUS_ENABLE)
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->update([
                'status' => $status,
                'remark' => $remark,
                'update_time' => time(),
            ]);
    }

    /**
     * 更新用户信息
     * @param $taskId
     * @param $user
     * @return int
     */
    public function updateUserInfoByTaskId($taskId, $user)
    {
        return $this->model
            ->where('task_id', $taskId)
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->update([
                'user_id' => $user['user_id'],
                'mobile' => $user['mobile'],
                'realname' => $user['realname'],
                'city' => $user['city'],
                'campus' => $user['campus'],
                'role' => $user['role'],
                'update_time' => time(),
            ]);
    }

    /**
     * 更新推送信息
     * @param $messageId
     * @param $push
     * @param string $remark
     * @return int
     */
    public function updatePushInfoById($messageId, $push, $remark = '')
    {
        return $this->model
            ->where('id', $messageId)
            ->where('is_deleted', MessageConst::IS_DELETED_NO)
            ->update([
                'url' => $push['url'],
                'method' => $push['method'],
                'body' => $push['body'],
                'result' => $push['result'],
                'status' => $push['status'],
                'remark' => $remark,
                'update_time' => time(),
            ]);
    }

    /**
     * 插入数据到分表
     * @param $data
     * @param string $method
     * @return mixed
     */
    public function add($data, $method = 'insertGetId')
    {
        $tableName = $this->model->getTable();
        $subTableName = $tableName . '_' . date('Ym');
        $data['create_time'] = !empty($data['create_time']) ? $data['create_time'] : time();
        $data['update_time'] = !empty($data['update_time']) ? $data['update_time'] : time();
        $res = $this->model->setTable($subTableName)->$method($data);
        $this->model->setTable($tableName);
        return $res;
    }

    /**
     * Clone table
     * @param string $tableName
     * @param string $newTable
     * @return bool
     */
    public function cloneTable($tableName = '', $newTable = '')
    {
        $prefix = env('DB_PREFIX');
        $tableName = $tableName ?: $this->model->getTable();
        $newTable = $newTable ?: $tableName . date('_Ym', time() + 28 * 86400);
        $sql = "CREATE TABLE IF NOT EXISTS {$prefix}$newTable (LIKE {$prefix}$tableName INCLUDING ALL) INHERITS ({$prefix}$tableName);";
        DB::statement($sql);
        return true;
    }

}